package com.mycompany.repository.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import com.mycompany.entity.Period;
import com.mycompany.repository.PeriodDao;

@Repository
public class PeriodDaoImpl implements PeriodDao {
	
	private EntityManager em;
	String sqlQuery="";
	

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.em = entityManager;
	}

	@Override
	public void persist(Period period) {
		em.persist(period);
	}

	@Override
	public void merge(Period period) {
		em.merge(period);
	}

	@Override
	public void remove(Period period) {
		period.setActiveFlg(false);
		em.merge(period);
	}

	@Override
	public Period findById(Integer periodId) {
		sqlQuery = "select x from Period x where x.periodId= :periodId and x.activeFlg = 1";
		return (Period) em.createQuery(sqlQuery).setParameter("periodId", periodId).getSingleResult();
	}

	@Override
	public Period find(Period period) {
		sqlQuery = "select x from Period x where x.periodId= :periodId and x.activeFlg = 1";
		return (Period) em.createQuery(sqlQuery).setParameter("periodId", period.getPeriodId()).getSingleResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Period> findAll() {
		sqlQuery = "select x from Period x where x.activeFlg = 1 ORDER BY x.periodId DESC ";
        return em.createQuery(sqlQuery).getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Period> findListByCodition(Period period) {
        sqlQuery = "select x from Period x where 1=1 and  x.activeFlg = 1 ";
        
        if(period.getPeriodId() != null ){
			sqlQuery = sqlQuery+" AND x.periodId = '"+period.getPeriodId()+"' ";
		}
        
		if(period.getEndDt()!= null ){
			sqlQuery = sqlQuery+" AND x.endDt like '"+period.getEndDt()+"' ";
		}
		
		if(period.getName()!= null ){
			sqlQuery = sqlQuery+" AND x.name like '%"+period.getName()+"%' ";
		}
		sqlQuery = sqlQuery+ "  ORDER BY x.periodId DESC  "; 
        return em.createQuery(sqlQuery).getResultList(); 
	}

	
}
